import axios, { AxiosInstance, AxiosResponse } from "axios";
import store from "@/store/index";
import { setLogin } from "@/store/modules/user";

const instance: AxiosInstance = axios.create({
  baseURL: "http://localhost:5173",
});
// 获取 Redux store 的引用
const reduxStore = store;

// 封装请求函数
const request = <T, D>(
  url: string = "",
  data: D = {} as D,
  method: string = "GET"
): Promise<AxiosResponse<T>> => {
  return instance.request<T>({
    url,
    method,
    data,
  });
};
// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    if (config.url?.includes("back")) {
      if (config.url?.includes("api")) {
        const token: string | null = localStorage.getItem("token");
        if (token) {
          config.headers["Authorization"] = token;
        }
      }
    } else {
      const { login, userInfo } = reduxStore.getState().user;
      if (config.url?.includes("api")) {
        if (!login) {
          // 调用setLogin
          reduxStore.dispatch(setLogin(true));
          return Promise.reject(new Error("请先登录"));
        } else {
          const token: string | undefined = userInfo.token;
          config.headers["Authorization"] = token;
        }
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default request;
